import pandas as pd
import time

from 海龟策略实盘.utils.commons import retry_wrapper
from 海龟策略实盘.config import symbol_config, exchange


# ===判断当前持仓模式
def if_oneway_mode():
    """
    判断当前合约持仓模式。必须得是单向模式。如果是双向模式，就改为单向持仓模式。
    判断持仓情况，False为单向持仓，True为单向持仓
    """
    # GET /fapi/v1/positionSide/dual (HMAC SHA256)
    positionSide = retry_wrapper(exchange.fapiPrivateGetPositionSideDual, func_name='查看合约持仓模式')

    if positionSide['dualSidePosition']:
        params = {
            'dualSidePosition': 'false',
            'timestamp': int(time.time() * 1000),
        }
        retry_wrapper(exchange.fapiPrivatePostPositionSideDual, params, func_name='更改合约持仓模式')
        print('更改持仓模式为：单向持仓\n')
    else:
        print('当前持仓模式：单向持仓\n')


# 重置一下页面最大杠杆
def reset_leverage(max_leverage=3):
    # 获取账户持仓风险(这里有杠杆数据)
    # GET /fapi/v2/positionRisk (HMAC SHA256)
    position_risk = retry_wrapper(exchange.fapiPrivate_get_positionrisk,
                                  params={'timestamp': int(time.time() * 1000)},
                                  func_name='fapiPrivate_get_positionrisk')
    position_risk = pd.DataFrame(position_risk)  # 将数据转成DataFrame
    position_risk.set_index('symbol', inplace=True)  # 将symbol设为index

    # 遍历每一个可以持仓的币种，修改页面最大杠杆
    for symbol, row in position_risk.iterrows():
        _leverage = row['leverage']
        if _leverage != max_leverage:
            # 设置杠杆
            # POST /fapi/v1/leverage (HMAC SHA256)
            params = {
                'symbol': symbol,
                'leverage': max_leverage,
                'timestamp': int(time.time() * 1000),
            }
            retry_wrapper(exchange.fapiPrivate_post_leverage,
                          params=params,
                          func_name='fapiPrivate_post_leverage')

    print('修改页面最大杠杆操作完成')


# ===获取U本位合约账户净值(不包含未实现盈亏)
def get_position_equity():
    equity = retry_wrapper(exchange.fapiPrivate_get_account, func_name='fapiPrivate_get_account')  # 获取账户净值
    equity = pd.DataFrame(equity['assets'])
    equity = float(equity[equity['asset'] == 'USDT']['walletBalance'])
    print('账户金额：%.2f' % equity)
    if equity <= 0:
        print('账户USDT金额小于等于0， 无法进行交议，退出程序')
        exit()
    return equity


# ===获取当前持仓信息
def bn_fetch_future_position(account_info):
    """
    获取u本位账户的持仓信息、账户余额信息
    """

    now_milliseconds = int(time.time() * 1000)
    params = {'timestamp': now_milliseconds}
    # GET /fapi/v2/account (HMAC SHA256)
    response = exchange.fapiPrivateV2GetAccount(params)

    assets_df = pd.DataFrame(response['assets'])
    assets_df.set_index('asset', inplace=True)
    assets_df = assets_df[assets_df.index.isin(['USDT'])]

    positions_df = pd.DataFrame(response['positions'])
    positions_df.set_index('symbol', inplace=True)
    positions_df = positions_df[positions_df.index.isin(symbol_config.keys())]

    balance = float(assets_df.loc['USDT', 'marginBalance'])  # 保证金余额
    account_info['账户权益'] = balance

    account_info['持仓量'] = positions_df['positionAmt'].astype(float)
    account_info['持仓方向'] = account_info['持仓量'].apply(
        lambda x: 1 if float(x) > 0 else (-1 if float(x) < 0 else 0))

    account_info['持仓收益'] = positions_df['unrealizedProfit'].astype(float).round(0)
    account_info['持仓均价'] = positions_df['entryPrice'].astype(float).round(0)
    profit = account_info['持仓收益'].sum()
    account_info['分配比例'] = pd.DataFrame(symbol_config).T['position']
    account_info['分配资金'] = (balance - profit) * account_info['分配比例']

    return account_info
